package cn.st4rlight.util.delay;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

import lombok.Data;

/**
 * 延迟执行任务，注意该延迟加载是不会加锁的
 *
 * @author st4rlight <st4rlight@163.com>
 * Created on 2024-07-01
 */
@Data
public class DelayRunnableTask implements Delayed, Runnable {

    private long delayMillis;
    private long createTime;
    private Runnable runnable;

    public DelayRunnableTask(long delayMillis, Runnable runnable) {
        this.delayMillis = delayMillis;
        this.createTime = System.currentTimeMillis();
        this.runnable = runnable;
    }

    @Override
    public int compareTo(Delayed o) {
        DelayRunnableTask other = (DelayRunnableTask) o;
        Long currTrigger = this.getCreateTime() + this.getDelayMillis();
        Long otherTrigger = other.getDelayMillis() + other.getCreateTime();
        return currTrigger.compareTo(otherTrigger);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long remain = this.getCreateTime() + this.getDelayMillis() - System.currentTimeMillis();
        remain = Math.max(remain, 0);
        return unit.convert(remain, TimeUnit.MILLISECONDS);
    }

    @Override
    public void run() {
        this.getRunnable().run();
    }
}
